package com.vgooo.client.vchannel;

import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Handler;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SlidingDrawer.OnDrawerCloseListener;
import android.widget.SlidingDrawer.OnDrawerOpenListener;

import com.vgooo.client.ui.MSlidingDrawer;

import com.vgooo.bean.NewsPing;
import com.vgooo.client.Main;
import com.vgooo.client.R;
import com.vgooo.client.VGActivity;
import com.vgooo.client.VGApplication;
import com.vgooo.client.ViewLayout;
import com.vgooo.client.ui.PullDownView;
import com.vgooo.client.ui.PullDownView.OnPullDownListener;
import com.vgooo.util.BitmapUtils;
import com.vgooo.util.DataApi;
import com.vgooo.util.DebugTools;
import com.vgooo.util.GSonTools;
import com.vgooo.util.HttpUtils;
import com.vgooo.util.JsonParserUtils;
import com.vgooo.util.Loading;
import com.vgooo.util.Loading.Progress;
import com.vgooo.util.UmengUtils;
import com.vgooo.util.Utils;

public class PingActivity_V2{
	public final static int PING_SUCCESS = 0xfbad;
	public final static int PING_FAIL = PING_SUCCESS + 1;

	private final static String className = "PingActivity";
	public final static String TYPE_NEWS = "new";
	public final static String TYPE_PROD = "prod";
	public final static String TYPE_ALBUM = "pic";
	public boolean isQuote = false;
	public boolean isCancle = false;
	public boolean isSuccess = false;

	private LayoutInflater inflater;
	private EditText editText;
	private Context context;
	private VGActivity cparent;
	private Handler handler;
	private Button publishButton;
	private Button cancelButton;
	private View feedBack;

	private String type;
	private String id;
	private String uid;
	private String feedback_content;
	private String parent_id;

	public AlertDialog alertDialog;

	private PullDownView mPullDownView; // 下拉刷新控件 ，上拉显示更多
	private List<NewsPing> newsPings;// 所有的评论
	private ListView pingList;// 评论列表
	private PingAdapter pingAdapter;// 评论列表适配器
	private int pingAllPage = 0;// 评论分页页数 默认为0
	private int pingCurrentPage = 1;// 评论目前所在的页数 默认在第0页
	private int pingAllCount = 0;// 所有的评论数 默认评论数为0
	private int pingPerPage = 10;// 每一页的评论数 默认每一页评论数为5
	private String total;// 总评论数
	public boolean isShowPing = false;// 是否正在显示评论

	private boolean morePing = true;// 是否还有更多的评论

	private boolean isRefresh = false;

	// public boolean isFirstLoadingPing = true;

	// private View bodyLayout, pingLayout;// 手机、评论详情布局
	private View pingNoex, pingEx; // 显示、隐藏评论
	// private View boayView ;
	private TextView pingCount;// 新闻评论数
	private TextView pingCount2;// 新闻评论数
	private ImageView showPingView, hidePingView, feedBackView1, feedBackView2, ctHandle;
	// private android.view.View.OnClickListener showPingListener;
	private android.view.View.OnClickListener showPingListener,
			feedBackListener;
	
	private MSlidingDrawer slidingDrawer;
	
	OnPullDownListener onPullDownListener;

	private Animation bottomIn, bottomOut;


	public PingActivity_V2(VGActivity context, String type) {
		super();
		this.cparent = context;
		this.context = context;
		this.type = type;
		isRefresh = true;
		initAnimation();
		inflater = LayoutInflater.from(context);
		
	}

	public void initView(View detailVeiw,  View pingEx) {
		// this.boayView = boayView;
		this.pingEx = pingEx;
		this.pingCount2 = (TextView) detailVeiw
				.findViewById(R.id.ping_layout_tv_e);
		this.mPullDownView = (PullDownView) detailVeiw
				.findViewById(R.id.ping_layout_ListView);
		this.pingList = mPullDownView.getListView();
		this.pingList.setOnScrollListener(BitmapUtils.onScrollListener);
		hidePingView = (ImageView) detailVeiw
				.findViewById(R.id.ping_layout_more);

		slidingDrawer = (MSlidingDrawer) detailVeiw.findViewById(R.id.slidingdrawer);
		
		slidingDrawer.setmTouchableId(R.id.ping_layout_edit);
		slidingDrawer.setmPointer(R.id.ping_layout_ex);

		feedBackView2 = (ImageView) detailVeiw
				.findViewById(R.id.ping_layout_edit);
		

		ctHandle = (ImageView) detailVeiw.findViewById(R.id.ping_layout_more);		
		
		addListener();
		
	}

	public void setupView(String pingCounts, String id) {
		this.id = id;
		pingAllCount = Integer.parseInt(pingCounts);
		initPingCoutView();
		pingCurrentPage = 1;
		int ps = 0;
		if ((ps = pingAllCount / pingPerPage) == 0) {
			// 刚好整除时，所得的商就是页数
			pingAllPage = ps;
		} else {
			// 不能整除时，页数为商加一
			pingAllPage = ps + 1;
		}
		isShowPing = false;
		

		try {
			showPing();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			UmengUtils.onError(context, e.toString());
		}
	}

	private void initAnimation() {
		bottomIn = AnimationUtils.loadAnimation(context, R.anim.bottom_in);
		bottomOut = AnimationUtils.loadAnimation(context, R.anim.bottom_out);
	}

	private void initPingCoutView() {
		if (pingAllCount < 1) {
			morePing = false;
		} else {
			morePing = true;
		}
		initPingPage(pingAllCount);
		pingCount2.setText(pingAllCount + "");
	}

	private void setPingCountView() {
		initPingPage(pingAllCount);
		pingCount2.setText(pingAllCount + "");
	}

	private void addListener() {


		// 设置评论列表上拉刷新，下拉显示更多监听器
		onPullDownListener = new OnPullDownListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				try {
					refresh();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mPullDownView.notifyDidRefresh();
			}

			@Override
			public void onMore() {
				// TODO Auto-generated method stub
				try {
					if (morePing) {
						isRefresh = false;
						showPing();
					} else {
						// 告诉它获取更多完毕
						// Toast.makeText(context, "评论加载完毕。。。",
						// Toast.LENGTH_LONG)
						// .show();
						// 诉它数据加载完毕;
						mPullDownView.notifyDidLoad();
						// 告诉它获取更多完毕
						mPullDownView.notifyDidMore();

						mPullDownView.notifyNOMore();
						if (pingCurrentPage == 0) {
							// 暂无评论
							// mPullDownView.n
							mPullDownView.notifyHasNone();
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					UmengUtils.onError(context, e.toString());
				}
			}
		};
		mPullDownView.setOnPullDownListener(onPullDownListener);

		showPingListener = new android.view.View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(!isShowPing){
					return ;
				}
				if (pingCurrentPage == 1) {
					DebugTools.log(className,
							"OnClickListener 你单击了=>”查看评论“  执行showPing()");
					try {
						showPing();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						UmengUtils.onError(context, e.toString());
					}
				}

				// showPingView();
				isShowPing = true;
				pingEx.startAnimation(bottomOut);

			}
		};
		hidePingView.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(!isShowPing){
					return ;
				}
				isShowPing = false;
				pingEx.startAnimation(bottomOut);
			}
		});
		feedBackListener = new android.view.View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				DebugTools.log(className,
						"OnClickListener() 你单击了=>”评论“" + v.getId());
				showDialog(context);
			}
		};
		feedBackView2.setOnClickListener(feedBackListener);

		slidingDrawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
			
			@Override
			public void onDrawerOpened() {
				ctHandle.setImageResource(R.drawable.ping_more_ex);
				
			}
		});
		slidingDrawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {
			
			@Override
			public void onDrawerClosed() {

				ctHandle.setImageResource(R.drawable.ping_more);
				
			}
		});
		
	}

	public void showDialog(Context context) {

		feedBack = inflater.inflate(R.layout.ping_feed_back2, null);
		editText = (EditText) feedBack
				.findViewById(R.id.ping_feed_back_content);

		publishButton = (Button) feedBack
				.findViewById(R.id.ping_feed_back_content_publish);
		cancelButton = (Button) feedBack
				.findViewById(R.id.ping_feed_back_content_cancel);
		publishButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Utils.hideSoftInput(editText);
				feedback();
			}
		});
		cancelButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Utils.hideSoftInput(editText);
				cancelDialog();
			}
		});

		cparent.addContentView(feedBack, new LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		editText.requestFocus();
		Utils.showSoftInput(editText);

	}

	private InputMethodManager getSystemService(String inputMethodService) {
		// TODO Auto-generated method stub
		return null;
	}

	private void cancelDialog() {
		editText.setText(null);
		feedBack.setVisibility(View.GONE);
	}

	private void feedback() {
		if (VGApplication.userInfo == null || !VGApplication.userInfo.isLogin) {
			Main.loginIntent.putExtra(ViewLayout.TAB_TAG_LOGIN, false);
			ViewLayout.setViewPre(true, "登录", ViewLayout.TAB_TAG_LOGIN,
					R.id.login, cparent);
			// alertDialog.cancel();
			return;

		} else {
			this.uid = VGApplication.userInfo.user_id;
		}

		feedback_content = editText.getText().toString().trim();
		if (feedback_content == null || "".equals(feedback_content)) {
			editText.setError("评论不能为空！");
			Utils.showSoftInput(editText);
			return;
		}
		feedback_content = URLEncoder.encode(feedback_content);
		String urlPath = HttpUtils.BASE_URI + "feedback?type=" + type + "&id="
				+ id + "&uid=" + uid + "&feedback_content=" + feedback_content;
		if (parent_id != null && !"".equals(parent_id)) {
			urlPath = HttpUtils.BASE_URI + "feedback?type=" + type + "&id="
					+ id + "&uid=" + uid + "&parent_id=" + parent_id
					+ "&feedback_content=" + feedback_content;
		}
		new FeedbackAsync().execute(urlPath);
	}

	public void doClick(View v) {
		switch (v.getId()) {
		case R.id.ping_feed_back_content_publish:
			Utils.hideSoftInput(editText);
			feedback();
			break;

		case R.id.ping_feed_back_content_cancel:
			Utils.hideSoftInput(editText);
			alertDialog.cancel();
			break;

		case R.id.ping_layout_more:
			break;
		case R.id.ping_layout_no_ex_more:
			// showPingView();
			// if (pingCurrentPage == 1) {
			// DebugTools.log(className, "doClick 你单击了=>”查看评论“  执行showPing()");
			// try {
			// showPing();
			// } catch (Exception e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// UmengUtils.onError(context, e.toString());
			// }
			// }
			break;

		case R.id.ping_item_quote:
			parent_id = (String) v.getTag();
			DebugTools.log(className, "doClick() 你单击了=>”引用“" + parent_id);
			showDialog(context);
			break;

		case R.id.ping_layout_no_ex_edit:
		case R.id.ping_layout_edit:
			DebugTools.log(className, "doClick() 你单击了=>”评论“" + v.getId());
			showDialog(context);

			break;

		default:
			break;
		}
	}

	class FeedbackAsync extends AsyncTask<String, String, String> {

		private Progress dialog;

		public FeedbackAsync() {
			super();
			this.dialog = Loading.startProgress(cparent);
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			String result = "";
			try {
				result = HttpUtils.getJsonString(params[0]);
				log(params[0]);
				log("result : " + result ) ;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				DebugTools.log(className, "error : " + e.toString());
				UmengUtils.onError(context, e.toString());
			}
			return result.trim();
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result == null || "0".equals(result) || "".equals(result)) {
				Toast.makeText(context, "评论失败", Toast.LENGTH_SHORT).show();
				DebugTools.log(className, " 评论失败 ！ result= " + result);
			} else {
				cancelDialog();
				if (isShowPing) {
					onPullDownListener.onRefresh();
				}
				Toast.makeText(context, "评论成功", Toast.LENGTH_SHORT).show();
				DebugTools.log(className, " 评论成功 ！ result= " + result);
			}

			dialog.cancel();
		}

	}

	class MyClickListener implements OnClickListener {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			feedback();
		}

	}

	// private void showPingView() {
	// if(!canClick){
	// return ;
	// }
	// canClick = false ;
	// if (isShowPing) {
	// pingEx.startAnimation(bottomIn);
	// } else {
	// pingEx.startAnimation(bottomOut);
	// }
	// }

	/**
	 * 加载评论信息
	 */
	public void showPing() throws Exception {
		if (morePing) {
			new PingAsyncLoader(context).execute("");
		} else {
			// pingEx.setVisibility(View.INVISIBLE);

			pingAdapter = new PingAdapter(null, context);
			pingList.setAdapter(pingAdapter);
			mPullDownView.enableAutoFetchMore(true, 1);
			// 诉它数据加载完毕;
			mPullDownView.notifyDidLoad();
			// 告诉它获取更多完毕
			mPullDownView.notifyDidMore();
			// 告诉它没有了
			mPullDownView.notifyNOMore();
			mPullDownView.notifyHasNone();

			// pingEx.setVisibility(View.VISIBLE);
			// pingEx.startAnimation(bottomOut);

		}

	}

	/**
	 * 刷新
	 * 
	 * @throws Exception
	 */
	private void refresh() throws Exception {
		pingCurrentPage = 1;
		if (pingAllCount > 0) {
			morePing = true;
		} else {
			morePing = false;
		}
		isRefresh = true;
		showPing();
	}

	/**
	 * 初始化分页信息
	 */
	private void initPingPage(int pingCounts) {
		// pingCurrentPage = 1;
		pingAllCount = pingCounts;// 评论总条数
		int ps = 0;
		if ((ps = pingAllCount / pingPerPage) == 0) {
			// 刚好整除时，所得的商就是页数
			pingAllPage = ps;
		} else {
			// 不能整除时，页数为商加一
			pingAllPage = ps + 1;
		}
	}

	/**
	 * 获取指定页的评论信息
	 * 
	 * @param page
	 *            指定的页
	 * @param per
	 *            每页评论条数
	 * @return 评论的List集合
	 */
	private List<NewsPing> getPing(int page, int per) throws Exception {
		// String urlPath = HttpUtils.BASE_URI + "newsping?id=" +
		// newsInfo.news_id
		// + "&page=" + page + "&per=" + per;
		String urlPath = null;
		String jsonString = null;
		Map<String, Object> infos = null;
		List<Map<String, Object>> pingInfos = null;
		try {
			urlPath = HttpUtils.BASE_URI + DataApi.KEY_PINGS + "?type=" + type
					+ "&id=" + id + "&page=" + pingCurrentPage + "&per=" + per;

			jsonString = HttpUtils.getJsonString(urlPath);

			infos = GSonTools.getObjectMaps(jsonString);

			morePing = (Boolean) infos.get("more");
			total = (String) infos.get("total");
			pingAllCount = Integer.parseInt(total);
			if (PingActivity_V2.TYPE_NEWS.equals(type)
					|| PingActivity_V2.TYPE_ALBUM.equals(type)) {
				pingInfos = (List<Map<String, Object>>) infos.get("feedback");
				return JsonParserUtils.getNewsPings(pingInfos);
			} else if (PingActivity_V2.TYPE_PROD.equals(type)) {
				pingInfos = (List<Map<String, Object>>) infos.get("comments");
				// DebugTools.log(className, "pingInfos = " + pingInfos);
				return JsonParserUtils.getProdPings(pingInfos);
			}
		} finally {
			urlPath = null;
			jsonString = null;
			infos = null;
			pingInfos = null;
		}

		return null;
	}

	class PingAsyncLoader extends AsyncTask<String, String, List<NewsPing>> {
		private Context context;

		// private ProgressDialog dialog;

		public PingAsyncLoader(Context context) {
			super();
			this.context = context;
			// this.dialog = dialog;
		}

		@Override
		protected List<NewsPing> doInBackground(String... params) {
			// TODO Auto-generated method stub
			List<NewsPing> pingsAdd = null;
			try {
				// if (pingCurrentPage <= pingAllPage && morePing) {
				if (morePing) {
					pingsAdd = getPing(pingCurrentPage, pingPerPage);
					DebugTools.log(className, "评论的第" + pingCurrentPage + "页");
					pingCurrentPage++;
				}
				DebugTools.log(className, "评论的第" + pingCurrentPage + "页"
						+ "   pingAllPage =" + pingAllPage + "   morePing ="
						+ morePing);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return pingsAdd;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			// dialog.setCancelable(true);
			// dialog.cancel();
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(String... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(List<NewsPing> result) {
			// TODO Auto-generated method stub
			if (result != null && !result.isEmpty() && result.size() > 0) {
				if (isRefresh) {
					// isFirstLoadingPing = false;
					pingAdapter = new PingAdapter(result, context);
					pingList.setAdapter(pingAdapter);
					mPullDownView.enableAutoFetchMore(true, 1);
					setPingCountView();
				} else {
					pingAdapter.adddata(result);
				}
				// ListViewUtils.setListViewHeightBaseOnChildren(pingList);
			} else {
				String toastStr = null;
				if (isRefresh) {
					toastStr = "网络异常,刷新失败！";
				} else {
					toastStr = "网络异常,加载失败！";
				}
				Toast.makeText(context, toastStr, Toast.LENGTH_SHORT).show();
			}
			// 诉它数据加载完毕;
			mPullDownView.notifyDidLoad();
			// 告诉它获取更多完毕
			mPullDownView.notifyDidMore();

			if (!morePing || pingAllCount < 10) {
				// 告诉它获取更多完毕
				// Toast.makeText(context, "评论加载完毕。。。",
				// Toast.LENGTH_LONG).show();
				mPullDownView.notifyNOMore();
				// 告诉它没有了
				mPullDownView.notifyNOMore();
			}
			// BitmapUtils.cleanCache();
			super.onPostExecute(result);
		}

	}
	
	public static void log(String info ){
		Log.i(className, info);
	}
	
	

}
